<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px">
    <!-- <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ title }} </span>
    </template> -->
    <BasicForm @register="registerForm" >
      <template #domain="{ model, field }">
        <a-input v-model:value="model[field]" :addon-before="tenantConfig.domainProtocol"  :addon-after="tenantConfig.firstLevelDomain" />
      </template>

      <template #userName="{ model, field }">
        <template v-if="!model['id']">
          <a-input v-model:value="model[field]" readOnly placeholder="用户账号" @click="handleSelectUser"/>
        </template>
        <template v-else>
          <a-input v-model:value="model[field]" readOnly placeholder="用户账号" />
        </template>
      </template>
    </BasicForm>
  </BasicDrawer>
  <!--用户选择弹窗-->
  <UseSelectModal @register="registerAddUserModal" @select="submitSelectedUser"/>
</template>
<script lang="ts" setup>
import {computed, ref, unref} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {useModal} from '/@/components/Modal';
import UseSelectModal from '/@/views/system/user/UseSelectModal.vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './tenant.data';
import {getPlatformConfig, getTenant, saveOrUpdateTenant} from './tenant.api';
import {PlatformConfig} from './tenant.model';
import {useMessage} from '/@/hooks/web/useMessage';
import {listScene} from '/@/views/system/menu/scene/scene.api';
import {listTenantPackage} from "./package/tenantPackage.api"

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const tenantConfig = ref<PlatformConfig>({})
const selectdUser = ref<any>({})

const [registerAddUserModal, {openModal: openAddUserModal}] = useModal();

const wrapperCol: Partial<ColEx> = {
  xs: 24, // <576px
  sm: 24, // ≥576px
  md: 24, // ≥768px
  lg: 24, // ≥992px
  xl: 24, // ≥1200px
  xxl: 24, // ≥1600px
}

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: formSchema,
  labelWidth: 100,
  showActionButtonGroup: false,
  wrapperCol
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  console.timeEnd('open-drawer')
  //重置表单
  await resetFields();
  tenantConfig.value = await getPlatformConfig()
  setDrawerProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate;

  updateSchema({
    field: 'sceneId',
    component: 'ApiSelect',
    componentProps: ({ formModel, formActionType }) => {
      return {
        optionFilterProp: "label",
        labelField: 'name',
        valueField: 'id',
        showSearch: true,
        api: listScene,
        onSelect: async (value: any, option: any) => {
          formModel.packageId = undefined
          formModel.subPackageId = undefined
          console.log("option", option);
          const packageList = await listTenantPackage({sceneId: value})
          updatePackageIdScheme(packageList)
        },
        onOptionsChange: async (options) => {
          
        }
      }
    },
  })

  if (unref(isUpdate)) {
    //获取详情
    data.record = await getTenant({ id: data.record.id });
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });

    const packageList = await listTenantPackage({sceneId: data.record.sceneId})
    updatePackageIdScheme(packageList)
  }
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增租户' : '编辑租户'));
//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdateTenant({...values, userId: selectdUser.value.id}, isUpdate.value);
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

const updatePackageIdScheme = (packageList) => {
  const options = packageList.map(e => {
    return {key: e.id, label: e.name, value: e.id}
  })
  updateSchema({
    field: 'packageId',
    required: true,
    component: 'Select',
    componentProps: {
      optionFilterProp: "label",
      showSearch: true,
      options
    }
  })
  
  updateSchema({
    field: 'subPackageId',
    required: true,
    component: 'Select',
    componentProps: {
      optionFilterProp: "label",
      showSearch: true,
      options
    }
  })
}

const handleSelectUser = () => {
  openAddUserModal(true, {
    isTenantMember: false,
    singleSelect: true
  })
}

const submitSelectedUser = async (selectRows) => {
  if (selectRows && selectRows.length >= 1) {
    selectdUser.value = selectRows[0]
    console.log('selectRows', selectRows);
    setFieldsValue({userName: selectdUser.value.userName})
  }
}

</script>
